package com.vcaresolution.logistic.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vcaresolution.logistic.service.ServiceRegistry;

/**
 * <code>ApplicationInitializer</code> class is called during server startup. It is responsible for loading all the master
 * values and storing it in Application Scope.
 *
 * @author Snehal Shah
 * @version 1.0
 * @since ShipSoft 1.0
 */
public final class ApplicationInitializer implements ServletContextListener{

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(final ServletContextEvent event) {
		final ServletContext context = event.getServletContext();
		final ApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(context);

		final ServiceRegistry serviceRegistry = springContext.getBean(ServiceRegistry.class);
		
		context.setAttribute(ApplicationConstants.SECTORS_MODELATTRIBUTE,serviceRegistry.getSectorService().findByAll());
		context.setAttribute(ApplicationConstants.SECURITY_QUESTIONS_MODELATTRIBUTE,serviceRegistry.getSecurityquestionService().findByAll());
		context.setAttribute(ApplicationConstants.COUNTRYS_MODELATTRIBUTE,serviceRegistry.getCountryService().findByAll());
		
		loadCodeTables(serviceRegistry);
	}
	
	

	private void loadCodeTables(ServiceRegistry serviceRegistry) {
		System.out.println("Loading Code Tables == Start ");
		serviceRegistry.getCodetableService().loadCodeTables();
		System.out.println("Total Code Tables Found :: "+ApplicationConstants.CODETABLELS.size());
		System.out.println("Total Code Table VALUES Found :: "+ApplicationConstants.CODETABLELVALUES.size());		
		System.out.println("Loading Code Tables == END  ");
	}



	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(final ServletContextEvent event) {
		System.out.println("This part will be called when server stops");
	}
	
}
